import { ActionType, EditableFormInstance, EditableProTable, heILIntl, ProCard, ProColumns, ProForm, ProTable } from "@ant-design/pro-components";
import { Button, Card, Checkbox, Col, Flex, Input, Row, Space, Table, TableColumnProps, TableColumnsType, TableColumnType, Tabs, Tag } from "antd";
import { TabsProps } from "antd/lib";
import {Splitter} from "antd";
import { useRef, useState } from "react";
import { s_getcommontableinfo, status2text } from "@/services/basis";
import { useModel } from "@umijs/max";


const App:React.FC=()=>{
    const [selectedRole,setSelectedRole]=useState<DataType[]>([]);
    const [selectedMenuID,setSelectedMenuID]=useState([]);
    const [selectedRoutes,setSelectedRoutes]=useState<DataType2[]>([]);

    const [dataSource2,setDataSource2]=useState([]);

    const {initialState}=useModel('@@initialState');
    const x_id=initialState?.currentUser?.x_id;

    const table_ref=useRef<ActionType>();
    const form_ref=useRef<EditableFormInstance>();
    const table_ref2=useRef<ActionType>();
    const form_ref2=useRef<EditableFormInstance>();
    const table_ref3=useRef<ActionType>();
    const form_ref3=useRef<EditableFormInstance>();

   
    const tableform_ref2=useRef<EditableFormInstance>();
    const tableform_ref3=useRef<EditableFormInstance>();

   //角色列表定义 
    interface DataType{
        id:number,
        code:string,
        name:string,
        status:number,
        modifyat?:string,
        mofifyuser?:string,
    }

    const columns:ProColumns<DataType>[]=[
        { key:'id',dataIndex:'id',title:'ID',},
        { key:'code', dataIndex:'code',title:'编码', },
        { dataIndex:'name', title:'角色名称',},
        { dataIndex:'status',title:'状态',
             render:(text:any)=>text==1?<Tag>正常</Tag>:text==2?<Tag color="blue">冻结</Tag>:<Tag color="red">删除</Tag>,
        }
    ];
  
//菜单权限列表定义
    interface DataType2{
        rid:number,
       id:number,x_id:number,role_id:number,
       mcode:string,mname:string,model:string,ischeck:string[],
       isend:number,
    }
    const columns2:ProColumns<DataType2>[]=[
        {dataIndex:'rid',title:'rid',editable:false,width:50,ellipsis:true,hidden:true},
        {dataIndex:'id',title:'ID',width:50,editable:false,},
        {dataIndex:'x_id',hidden:true},{dataIndex:'role_id',hidden:true},
        {dataIndex:'model',title:'模块',width:100,editable:false,
          },
        {dataIndex:'name',hidden:true},
        {dataIndex:'dsc',title:'功能项',width:100,editable:false},
        {dataIndex:'ischeck',title:'授权',
            valueType:'checkbox',valueEnum:{'1':{text:'授权'}}}
    ];
    
    //操作权限定义
    interface DataType3{
        rid:number,
        id:number,
        route_id:number,
        name:string,
        dsc:string,
        ischeck:string[],
     }

    const columns3:ProColumns<DataType3>[]=[
        {dataIndex:'rid',title:'rid',width:80,editable:false,ellipsis:true},
        {dataIndex:'id',title:'ID',width:80,editable:false},
        {dataIndex:'route_id',hidden:true,editable:false},
        {dataIndex:'dsc',title:'操作名',editable:false,width:120},
        {dataIndex:'name',title:'名称',hidden:true,editable:false},
        {dataIndex:'ischeck',title:'授权',width:80,
            valueType:'checkbox',valueEnum:{'1':{text:'授权'}}}
    ];

    const items:TabsProps['items']=[
        {
            key: '1',
            label: '系统授权管理',
            children:<>
            <Splitter  style={{height:'100%'}} >
                <Splitter.Panel defaultSize={500}>
                    {/* {JSON.stringify(dataSource2)} */}
                    <ProCard style={{height:600,overflow:'auto'}}>
                <ProForm formRef={tableform_ref2} submitter={false}>
                <EditableProTable<DataType2>
                name='table_route'
                actionRef={table_ref2}
                editableFormRef={form_ref2}
                rowKey='rid'
                columns={columns2}
                // dataSource={dataSource2}
                // request={async ()=>{
                //     // x_id,cate_id,id,source,fdata
                //     // const x=await s_getcommontableinfo({x_id,source:'base_role',id:0});
                //     return {
                //         data:dataSource2,
                //         success:true,
                //     };
                // }}
                editable={{
                    // editableKeys:[1,2,3,4,5,6],
                    type:'multiple',
                    // 奇怪，参数record无法选中当前行。。。2025-2-16
                    // onValuesChange:(record,records)=>{
                    //     alert(JSON.stringify(record));
                    //  },
                    
                }}
                rowSelection={{
                    type:'radio',
                    async onChange(selectedRowKeys, selectedRows:any, info) {
                       
                        setSelectedRoutes(selectedRows);
                        const x=await s_getcommontableinfo({x_id,source:'v_grant_operate',
                            fdata:{
                                route_id:selectedRows.length>0?selectedRows[0].id:0,
                                role_id:selectedRole.length>0?selectedRole[0].id:0,
                            }});

                            // alert(JSON.stringify(x.data[0]));
                        tableform_ref3.current?.setFieldValue('table_operate',x.data[0]);
                        x.data[0].map((item:any)=>{
                            table_ref3.current?.startEditable(item.rid);
                        });
                      
                    },
                }}
             
                />
                </ProForm>
                </ProCard>
                </Splitter.Panel>
                <Splitter.Panel>
               <ProCard style={{height:600,overflow:'auto'}}>
                {JSON.stringify(selectedRoutes)}
                <ProForm formRef={tableform_ref3} submitter={false}>
                <EditableProTable<DataType3>
                name='table_operate'
                actionRef={table_ref3}
                editableFormRef={form_ref3}
                rowKey='rid'
                columns={columns3}
                // request={async ()=>{
                //     const x=await s_getcommontableinfo({source:'v_grant_operate',x_id,
                //            fdata:{role_id:selectedRole.length>0?selectedRole[0].id:0,
                //                   route_id:selectedRoutes.length>0?selectedRoutes[0]?.id:0}});
                //     return {
                //         data:x.data[0],
                //         success:true,
                //     };
                // }}

                editable={{
                    // editableKeys:[1,2],
                    type:'multiple',
                    // onValuesChange:(record,records)=>alert(JSON.stringify(records)),
                }
                }
                />
                </ProForm>
                </ProCard> 
                </Splitter.Panel>

            </Splitter>
            
            </>,
        },
        {
            key:'2',
            label:'数据权限',
            children:<><ProForm name='tableform_ref3' submitter={false}>
            <EditableProTable<DataType3>
            name='table_operate'
            actionRef={table_ref3}
            editableFormRef={form_ref3}
            rowKey='rid'
            columns={columns3}
            // request={async ()=>{
            //     const x=await s_getcommontableinfo({source:'v_grant_operate',x_id,
            //            fdata:{role_id:selectedRole.length>0?selectedRole[0].id:0,
            //                   route_id:selectedRoutes.length>0?selectedRoutes[0]?.id:0}});
            //     return {
            //         data:x.data[0],
            //         success:true,
            //     };
            // }}

            editable={{
                // editableKeys:[1,2],
                type:'multiple',
                // onValuesChange:(record,records)=>alert(JSON.stringify(records)),
            }
            }
            />
            </ProForm></>,
        },
    ];
     
    interface Dt{
        id:number,
        status:string[],
        // status:number[],
      }

     const col:ProColumns<Dt>[]=[
        {dataIndex:'id',title:'ID'},
        {dataIndex:'status',title:'状态',
            valueType:'checkbox',
            // valueEnum:{"1":{text:'选中'}},
            valueEnum:{'1':{text:'选中'}},
         },
     ]

     const da:Dt[]=[
    //     {id:1,status:["1"]},
    //     {id:2,status:[""]},
    //     {id:3,status:["1"]},
    //     {id:4,status:[""]}
         {id:1,status:['1']},
        {id:2,status:['']},
        {id:3,status:['1']},
        {id:4,status:['']}
      ]

      //保存授权
      async function saveGrant(){
         const routeData=form_ref2.current?.getRowsData?.();
         const operateData=form_ref3.current?.getRowsData?.();
         
         const rdata=routeData?.filter((item:any)=>item.ischeck);
         const odata=operateData?.filter((item:any)=>item.ischeck);

         const tdata=rdata?rdata.map((item:any)=>item.dsc):[];
         const tdata2=odata?odata?.filter((item:any)=>item.ischeck).map((item:any)=>item.dsc):[];

         alert(JSON.stringify(tdata));
         alert(JSON.stringify(tdata2));

      }

      //取消授权
      function resetGrant(){
        table_ref.current?.reset?.();
        table_ref2.current?.reset?.();
        table_ref3.current?.reset?.();
      }

// 以下为表单区=======================================================================================================
    return(
        <>
        <Row gutter={8}>
            <Col span={6}>
            <Card style={{height:800}} title='角色列表' extra={<Space><Button>按角色授权</Button></Space>}>
                 {'当前选中的角色ID：'+JSON.stringify(selectedRole)}
                <ProTable<DataType>  
                   search={false}
                   columns={columns}   
                   rowSelection={{
                        type:'radio',
                        async onChange(selectedRowKeys:any, selectedRows:any, info) {
                            setSelectedRole(selectedRows);
                            // 按角色获取已授权的菜单列表
                            const x=await s_getcommontableinfo({x_id,source:'v_grant_route',
                                  fdata:{role_id:selectedRowKeys[0]}});
                            //   alert(JSON.stringify(x.data[0]));
                            // setDataSource2(x.data[0]);
                            tableform_ref2.current?.setFieldValue('table_route',x.data[0]);
                            x.data[0].map((item:any)=>{
                              table_ref2.current?.startEditable(item.rid);
                            });
                            
                        },
                    }} 
                   rowKey='id'
                   request={async ()=>{
                      const x=await s_getcommontableinfo({x_id,source:'base_role',id:0});
                      return {
                        data:x.data[0],
                        success:true,
                      }
                    }}
                    />
            </Card>
            </Col> 
            
            <Col span={18}>
            <Card style={{height:800}} title='权限列表' >
            {/* {JSON.stringify(dataSource2)} */}
              <Tabs tabBarExtraContent={<Space>
                  <Button onClick={()=>saveGrant()}>保存</Button>
                  <Button onClick={()=>resetGrant()}>取消</Button>
             </Space>} 
                   items={items} type="card"/>   

                <EditableProTable<Dt>
                actionRef={table_ref}
                editableFormRef={form_ref}
                rowKey='id'
                columns={col}
                // dataSource={da}
                // request={async ()=>(
                //     {data:da,
                //         success:true
                //     }
                // )}
                request={async ()=>{
                    const x=await s_getcommontableinfo({});
                    return {
                        data:da,
                        success:true
                       };
                }}

                editable={{
                    editableKeys:[1,2],
                    onValuesChange:(record,records)=>alert(JSON.stringify(records)),
                }}
                />
            </Card>
            </Col>          
        </Row>
    
     </>
);
}

export default App;